<template>
  <view class="dropdown">
    <view
      class="dropdown-item"
      v-for="(item, index) in tabList"
      :key="index"
      @click="clickHandler(item, item.key, item.id)"
      :style="{
        color: item.color
      }"
    >
      <text>{{ item.title }}</text>
      <u-icon
        class="icon"
        :name="item.icon == 'up' ? 'arrow-up' : 'arrow-down'"
        :color="item.color == 'black' ? '#1f2f3d' : '#e91900'"
        size="14"
      ></u-icon>
    </view>
    <u-popup
      :show="show"
      @close="close"
      @open="open"
      :closeOnClickOverlay="true"
    >
      <view class="popup-content">
        <view class="popup-input">
          <u--input
            prefixIcon="search"
            placeholder="请输入内容"
            v-model="inputvalue"
            border="bottom"
            clearable
          ></u--input>
          <view class="text" @click="handleSearch">搜索</view>
        </view>
        <scroll-view scroll-y="true" class="custom-list">
          <view
            class="custom-list-item"
            v-for="(item, index) in indexList"
            :key="index"
            @click="hanldeSelect(item)"
          >
            <u-icon
              name="checkbox-mark"
              color="#e91900"
              size="14"
              v-if="currentTitle == item.orgName"
            ></u-icon>
            <view class="custom-list-item-text">{{ item.orgName }}</view>
          </view>
        </scroll-view>
        <view class="button">
          <u-button
            class="custom-button"
            text="重置"
            @click="handleReset"
          ></u-button>
          <u-button
            class="custom-button"
            type="primary"
            text="确定"
            @click="handleOk"
          ></u-button>
        </view>
      </view>
    </u-popup>
  </view>
</template>

<script>
import { getOrgListApi, getRegionsIdListApi } from '@/api/org'
import { getCementEquipmentApi } from '@/api/mixing-plant/cement'
import { getStabilityEquipmentApi } from '@/api/mixing-plant/stability'
import { getAsphaltEquipmentsApi } from '@/api/mixing-plant/asphalt'
import dayjs from '@/utils/dayjs'
export default {
  components: {},
  props: {
    equipmentType: {
      type: String
    }
  },
  data() {
    return {
      // 2项目 3标段 4区域
      orgType: 2,
      show: false,
      inputvalue: '',
      tabList: [
        {
          title: '选择项目',
          id: '',
          icon: 'up',
          color: 'black',
          key: 2
        },
        {
          title: '选择标段',
          icon: 'up',
          id: '',
          color: 'black',
          key: 3
        },
        {
          title: '选择区域',
          id: '',
          icon: 'up',
          color: 'black',
          key: 4
        }
      ],
      currentKey: '',
      currentId: '',
      indexList: [],
      rootList: [],
      currentTitle: '',
      equipmentsList: [],
      allProject: [],
      allSection: [],
      allRegion: [],
      initialKey: '',
      initialId: '',
      initialTitle: ''
    }
  },
  methods: {
    // 获取组织列表
    async getEquipmentsList(type) {
      uni.showLoading({
        title: '数据加载中'
      })
      // 如果没有选择任何组织,则查询全部区域
      let params = {
        orgType: type ?? 4,
        orgIds: '',
        equipmentType: this.equipmentType
      }
      // 遍历tabList,如果id不为空,则将id拼接成字符串,并赋值给params.orgIds,如果密度更小的单位有id就用密度更小的(区域为密度最小的)
      this.tabList.forEach((val) => {
        if (val.id != '') {
          params.orgIds = val.id + ''
          params.orgType = val.key
        }
      })
      // 如果没有选择任何组织,则查询全部区域
      if (params.orgIds === '') {
        params.orgIds = this.allRegion.join(',')
        params.orgType = 4
      }
      let res
      if (this.equipmentType.indexOf('cement_concrete_mixer') !== -1) {
        // 水泥
        res = await getCementEquipmentApi(params)
        res.forEach((val) => {
          val.dischargeTime = val.dischargeTime
            ? dayjs(val.dischargeTime).format('YYYY-MM-DD HH:mm:ss')
            : '-'
          val.proportionMixtureStabilizedName =
            val.proportionMixtureStabilizedName ?? '-'
          val.actualVolume = val.actualVolume ?? '-'
          val.mixingTime = val.mixingTime ?? '-'
          val.pouringLocation = val.pouringLocation ?? '-'
        })
      } else if (
        this.equipmentType.indexOf('cement_stabilized_soil_mixer') !== -1
      ) {
        // 水稳
        res = await getStabilityEquipmentApi(params)
        res.forEach((val) => {
          val.dischargeTime = val.dischargeTime
            ? dayjs(val.dischargeTime).format('YYYY-MM-DD HH:mm:ss')
            : '-'
          val.proportionMixtureStabilizedName =
            val.proportionMixtureStabilizedName ?? '-'
          val.actualTotal = val.actualTotal ?? '-'
        })
      } else {
        res = await getAsphaltEquipmentsApi(params)
        res.forEach((val) => {
          val.dischargeTime = val.dischargeTime
            ? dayjs(val.dischargeTime).format('YYYY-MM-DD HH:mm:ss')
            : '-'
          val.worksSurfaceCourse = val.worksSurfaceCourse ?? '-'
          val.actualTotal = val.actualTotal ?? '-'
          val.proportionMixtureName = val.proportionMixtureName ?? '-'
          val.proportionMixtureName = val.proportionMixtureName ?? '-'
        })
      }
      this.equipmentsList = res
      this.$emit('changeCallBack')
      uni.hideLoading()
    },
    // 获取组织区域
    async getOrgList(type, first) {
      uni.showLoading({
        title: '数据加载中'
      })
      let filterRegions = ''
      // 如果是区域的话需要先筛选一遍有设备的区域
      if (type === 4) {
        let res = await getRegionsIdListApi({
          equipmentType: this.equipmentType
        })
        console.log(res)

        filterRegions = res.join(',')
      }
      // 父id
      let parentOrgIds = ''
      if (type == 3) {
        // 如果是标段就取项目id
        parentOrgIds = this.tabList[0].id
      } else if (type == 4) {
        // 如果是区域就取标段id,如果标段没有就取项目的
        parentOrgIds =
          this.tabList[1].id !== '' ? this.tabList[1].id : this.tabList[0].id
      }
      let params = {
        orgType: type,
        parentOrgIds: type == 2 ? '' : parentOrgIds,
        filterRegions: filterRegions
      }
      let res = await getOrgListApi(params)
      if (first) this.allRegion = res.map((val) => val.id)
      // if (type === 4) {
      //   this.allRegion = res.map(val => val.id)
      // } else if (type === 3) {
      //   this.allSection = res.map(val => val.id)
      // }
      this.rootList = res
      uni.hideLoading()
    },
    // 点击下拉列表
    async clickHandler(item, key, id) {
      await this.getOrgList(key)
      this.initialKey = key
      this.initialId = id
      this.initialTitle = item.title
      this.indexList = this.rootList
      this.show = true
      this.currentKey = key
      this.currentId = id
      this.currentTitle = item.title.includes('选择') ? '' : item.title
      this.changeTab(key)
    },
    // tab颜色和图标切换
    changeTab(key, title, id) {
      let obj = this.tabList[key - 2]
      if (key == 2) {
        this.tabList[1].title = '选择标段'
        this.tabList[1].id = ''
        this.tabList[2].title = '选择区域'
        this.tabList[2].id = ''
      } else if (key == 3) {
        this.tabList[2].title = '选择区域'
        this.tabList[2].id = ''
      }
      obj.icon = obj.icon == 'down' ? 'up' : 'down'
      obj.color = obj.color == 'red' ? 'black' : 'red'
      if (title && title != '') {
        obj.title = title
      } else {
        obj.title = ['选择项目', '选择标段', '选择区域'][this.currentKey - 2]
      }
      if (id && id != '') {
        this.$set(obj, 'id', id)
      } else {
        this.$set(obj, 'id', '')
      }
      this.tabList[key - 2] = uni.$u.deepClone(obj)
    },
    open() {},
    close() {
      this.show = false
      this.currentKey = this.initialKey
      this.currentTitle = this.initialTitle
      this.currentId = this.initialId
      this.changeTab(this.currentKey, this.currentTitle, this.currentId)
    },
    // 点击确定事件
    handleOk() {
      this.show = false
      this.inputvalue = ''
      this.changeTab(this.currentKey, this.currentTitle, this.currentId)
      if (this.currentKey != '') {
        this.getEquipmentsList(this.currentKey)
      }
    },
    // 选中事件
    hanldeSelect(item) {
      this.currentTitle = item.orgName
      this.currentId = item.id
    },
    // 重置
    handleReset() {
      this.currentTitle = ''
      this.currentId = ''
      this.tabList.forEach((val) => {
        if (val.key == this.currentKey) {
          val.title = ['选择项目', '选择标段', '选择区域'][this.currentKey - 2]
          val.id = ''
        }
      })
    },
    // 搜索
    handleSearch() {
      this.indexList = this.rootList.filter((val) => {
        return val.orgName.includes(this.inputvalue) != false
      })
    }
  }
}
</script>
<style lang="scss" scoped>
.dropdown {
  display: flex;
  padding: 30rpx 10rpx;
  background-color: #fff;
  //   justify-content: space-around;

  /deep/ .button {
    //   background-color: pink;
    display: flex;
    justify-content: space-between;
    margin: 20rpx 0;
    /deep/ & > .u-button {
      width: 45%;
    }
    /deep/ & > .u-button:nth-child(2) {
      background-color: red;
      border: none;
    }
  }
  & > .dropdown-item {
    display: flex;
    justify-content: center;
    font-size: 14px;

    width: 33.3%;
    text-overflow: ellipsis;
    overflow: hidden;
    white-space: nowrap;
    & > text {
      max-width: 80%;
      text-overflow: ellipsis;
      overflow: hidden;
      white-space: nowrap;
    }
    .icon {
      margin: 0 5px;
    }
  }
  .current {
    color: red;
  }
}

.popup-content {
  padding: 20rpx 20rpx 10rpx 20rpx;
  //   padding-bottom: env(safe-area-inset-bottom);
  .popup-input {
    display: flex;
    align-items: center;
    margin-bottom: 15px;
    height: 30px;

    .text {
      margin-left: 30rpx;
      color: #ababab;
    }
  }
  .custom-list {
    margin: 30rpx auto;
    height: 280px;
    .custom-list-item {
      display: flex;
      justify-content: center;
      align-items: center;
      width: 80%;
      margin: 20rpx auto;
      .custom-list-item-text {
        margin-left: 20rpx;
        max-width: 95%;
        text-overflow: ellipsis;
        overflow: hidden;
        white-space: nowrap;
      }
    }
  }
}
</style>
